import { useCallback } from 'react';
import { Modal } from 'antd';
import _ from 'lodash';
import type { ActionType } from '@ant-design/pro-components';
import type { ActionButtonConfig } from '../types';
import { t } from '@/components/utils';

/**
 * 处理操作相关逻辑
 */
export function usePageTemplateActions<T extends Record<string, any>>(
  rowKey: string | ((record: T) => string),
  crudService: any,
  handleFormOpen: (actionType: 'create' | 'edit' | 'copy' | 'view', record?: T) => void,
  customActions?: ActionButtonConfig[],
  onAction?: (actionType: string, record: T) => void | T | false,
) {
  // 删除单条记录
  const handleDelete = useCallback(
    (record: T, actionRef?: React.MutableRefObject<ActionType | undefined>) => {
      Modal.confirm({
        title: t('common', 'delete'),
        content: t('common', 'confirmDelete'),
        okType: 'danger',
        onOk: async () => {
          if (!crudService) return;
          try {
            const key = typeof rowKey === 'function' ? rowKey(record) : record[rowKey];
            await crudService.delete(key);
            actionRef?.current?.reload();
          } catch (error) {
            // 错误已在service中处理
          }
        },
      });
    },
    [crudService, rowKey],
  );

  // 默认操作处理
  const handleDefaultAction = useCallback(
    (actionType: string, record: T, actionRef?: React.MutableRefObject<ActionType | undefined>) => {
      const actionMap = {
        view: () => handleFormOpen('view', record),
        edit: () => handleFormOpen('edit', record),
        delete: () => handleDelete(record, actionRef),
        copy: () => handleFormOpen('copy', record),
      };

      const action = actionMap[actionType as keyof typeof actionMap];
      if (action) {
        action();
      } else {
        console.warn('Unknown action type:', actionType);
      }
    },
    [handleFormOpen, handleDelete],
  );

  // 统一的操作处理
  const handleAction = useCallback(
    (actionType: string, record: T, actionRef?: React.MutableRefObject<ActionType | undefined>) => {
      const useDefaultLogic = ['edit', 'view', 'copy', 'delete'].includes(actionType);
      const isCustomMode = !useDefaultLogic && !_.isEmpty(customActions) && onAction;

      if (isCustomMode) {
        onAction(actionType, record);
      } else {
        const processedRecord = onAction ? onAction(actionType, record) : record;
        if (processedRecord === false) return;
        handleDefaultAction(actionType, processedRecord as T, actionRef);
      }
    },
    [onAction, customActions, handleDefaultAction],
  );

  return {
    handleDelete,
    handleDefaultAction,
    handleAction,
  };
}

